// pages/submitGoods/submitGoods.js
var config = require("../../../config.js")
var util = require("../../../utils/MD5.js")
var request = require("../../../utils/request.js");
var req = require("../../../utils/reqGet.js");
var g = getApp().globalData;
var timer = null;
var ext = {};
Page({

  /**
   * 页面的初始数据
   */
  data: {
    payItem: 0,
    zk: 10, // 打折折扣
    showEwm: false,
    showCash: false,
    rechargeAmount: 0,
    zpid: 6,
    tableId: 11,
    ShopNo: 100010,
    payArr: ["现金支付", "支付宝", "微信支付"],
    payStr: "现金支付",
    zkArr: [9.5, 9, 8.5],
    people: "",
    mebInfo: {
      C_MB_PHONE: "",
    },
    keywords: "",
    mebno: "",
    setMember: false,
    setNumber: false,
    noMember: true,
    gradeId: "",
    pageIndex: 1,
    pageSize: 100,
    OrderNo: "",
    delIndex: [],
    ogList: [],
    num: 0,
    nMeb: true,
    useBalance: false,
    payAmount: 0,
    cashDialog: false,
    orderRecord: [],
    zkActive: -1,
    showZk: false,
    amt: 0,
    change: 0
  },

  onLoad(options) {
    // this.data.ShopNo = g.SHOP_NO || "100010";
    wx.getStorage({
      key: 'C_SHOP_NO',
      success: res => {
        this.data.ShopNo = res.data;
        console.log(res.data)
      },
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    wx.getStorage({
      key: 'result-list',
      success: res => {
        // this.data.amt = parseFloat(res.data.totalPrice);
        var amt = parseFloat(res.data.totalPrice);
        console.log(res.data.gList)
        this.setData({
          goodsList: res.data.gList,
          totalNum: res.data.totalNum,
          totalPrice: res.data.totalPrice,
          amt: res.data.totalPrice
        })
        this.data.gList = res.data.gList;

        wx.getStorage({
          key: 'mebInfo',
          success: rs => {
            if (rs.data) {
              this.setData({
                mebInfo: rs.data,
                mebno: rs.data.C_MB_NO,
                noMember: false,
                payAmount: amt
              });
            } else {
              this.setData({
                mebno: 0,
                mebInfo: null,
                payAmount: amt
              })
            }
          },
          fail: () => {
            this.data.payAmount = this.data.totalPrice;
          }
        })
      },
    })

    wx.getStorage({
      key: 'OP_INFO',
      success: res => {
        this.setData({
          opInfo: res.data,
        })
      },
    })

    wx.getStorage({
      key: 'order-record',
      success: res => {
        this.data.orderRecord = res.data;
      },
    })
  },

  hideZk(ev) {
    if (ev.currentTarget.dataset.t) {
      this.getPayAmount();
    }
    this.setData({
      showZk: false
    })
  },

  getPayAmount() {
    var odPrice = this.data.totalPrice * parseFloat(this.data.zk) / 10;
    if (this.data.useBalance) {
      if (odPrice - this.data.mebInfo.N_MB_AMOUNT > 0) {
        this.data.payAmount = odPrice - this.data.mebInfo.N_MB_AMOUNT;
      } else {
        this.data.payAmount = 0;
      }
    } else {
      this.data.payAmount = odPrice;
    }
    console.log(this.data.payAmount.toFixed(2))
    this.setData({
      payAmount: this.data.payAmount.toFixed(2),
    })
  },

  setPayAmount(ev) {
    if (/\./.test(ev.detail.value)) {
      this.data.amt = ev.detail.value.match(/\d+\.\d{0,2}/g)[0]
    } else {
      this.data.amt = parseInt(ev.detail.value);
    };

    if (this.data.payItem == 0) {
      if (parseFloat(this.data.amt) > this.data.payAmount) {
        var change = parseFloat(this.data.amt) - this.data.payAmount;
        this.setData({
          amt: this.data.amt,
          change: change.toFixed(2)
        })
      } else {
        this.setData({
          amt: this.data.amt,
        })
      }
    }
  },

  showZk() {
    this.setData({
      showZk: true,
    })
  },

  withoutMember() {
    wx.showModal({
      title: '提示',
      content: '填写会员信息的话会有很多优惠权限，记得在点菜的时候添加哦，不然后面就添不了了',
      showCancel: false,
    })
  },

  setZk(ev) {
    this.setData({
      zk: ev.currentTarget.dataset.d,
      zkActive: ev.currentTarget.dataset.i,
    })
  },

  setZkValue(ev) {
    var val = "";
    var zkActive = -1;
    if (/\./.test(ev.detail.value)) {
      if (ev.detail.value.match(/\d{1}\.\d{1}/g)) {
        val = ev.detail.value.match(/\d{1}\.\d{1}/g)[0]
      } else {
        val = ev.detail.value
      }
    } else {
      if (ev.detail.value.match(/\d{1}/g)) {
        val = ev.detail.value.match(/\d{1}/g)[0]
      } else {
        val = ev.detail.value
      }
    }
    for (var i = 0; i < this.data.zkArr.length; i++) {
      if (this.data.zkArr[i] == val) {
        zkActive = i
      }
    }
    this.setData({
      zk: val,
      zkActive
    })
  },

  setKeywords(ev) {
    this.setData({
      keywords: ev.detail.value
    })
  },

  /**
   * 获取会员列表
   */
  getMenberList() {
    var str = `ShopNo&keywords&gradeId&pageIndex&pageSize=${this.data.ShopNo}*${this.data.keywords}*0*${this.data.pageIndex}*${this.data.pageSize}`;
    var md5 = util.md5(str);
    wx.showLoading({
      title: '',
    })
    var data = {
      bNo: 1204,
      ShopNo: this.data.ShopNo,
      keywords: this.data.keywords,
      gradeId: 0,
      pageIndex: this.data.pageIndex,
      pageSize: this.data.pageSize,
      keytype: -1,
      MD5: md5.toUpperCase()
    };

    wx.request({
      url: config.requestUrl,
      data,
      success: res => {
        var d = res.data.replace(/\(|\)/g, "");
        var t = JSON.parse(d);
        if (t.mebdt.length > 0) {
          for (var i = 0; i < t.mebdt.length; i++) {
            if (t.mebdt[i].C_MB_NAME.length > 20) {
              t.mebdt[i].C_MB_NAME = t.mebdt[i].C_MB_NAME.substr(0, 20) + "..."
            }
          }
          wx.setStorage({
            key: 'member',
            data: t.mebdt[0],
          })
          this.setData({
            noMember: false,
            mebInfo: t.mebdt[0],
            mebno: t.mebdt[0].C_MB_NO,
          })
          this.hideDialog();
        } else {
          wx.showModal({
            title: '提示',
            content: '抱歉，暂无会员信息',
            showCancel: false,
          })
        }
        wx.hideLoading()
      }
    })
  },

  def() {},

  sureOrder() {
    if (!this.data.mebno) {
      this.data.mebno = 0
      this.order();
    } else {
      this.order();
    }
  },

  useBalance() {
    this.setData({
      useBalance: !this.data.useBalance
    })

    this.getPayAmount();
  },

  choosePayType() {
    wx.showActionSheet({
      itemList: this.data.payArr,
      success: res => {
        if (res.tapIndex != 0) {
          this.data.amt = this.data.payAmount;
        } else {
          this.data.amt = 0;
        }
        this.setData({
          payStr: this.data.payArr[res.tapIndex],
          payItem: res.tapIndex,
          payType: res.tapIndex + 1,
          amt: this.data.amt,
        })
        // if (res.tapIndex == 0) {

        // } else if (res.tapIndex == 1) {
        //   this.getPayEwm(3, OrderNo);
        // } else if (res.tapIndex == 2) {
        //   this.getPayEwm(1, OrderNo);
        // }
      }
    })
  },

  hideCash() {
    this.setData({
      showCash: false,
    })
  },

  showOrder() {
    this.setData({
      showCash: true
    })
  },

  sureCash() {
    this.order();
  },

  noChange() {
    this.setData({
      amt: this.data.payAmount
    }, () => {
      this.order();
    })
  },

  regCash() {
    wx.showLoading({
      title: '',
    })
    var str = `orderNo&payWay&zfls&payAmount=${this.data.OrderNo}*11**${this.data.rechargeAmount}`;
    var md5 = util.md5(str);
    var reqData = {
      bNo: 412,
      orderNo: this.data.OrderNo,
      payWay: 11,
      zfls: "",
      payAmount: this.data.rechargeAmount,
      opid: this.data.opInfo.n_ss_id,
      MD5: md5.toUpperCase()
    };

    wx.request({
      url: config.requestUrl,
      data: reqData,
      success: res => {
        var data2 = JSON.parse(res.data.replace(/\(|\)/g, ""));
        if (data2.code === "100") {
          this.data.orderRecord.push(this.data.totalPrice);
          wx.setStorage({
            key: 'order-record',
            data: this.data.orderRecord,
            success: res => {
              wx.removeStorage({
                key: 'result-list',
              })
              wx.removeStorage({
                key: 'mebInfo',
              })
              wx.showToast({
                title: '收款成功',
                mask: true,
                success: res => {
                  setTimeout(() => {
                    wx.redirectTo({
                      url: '/pages/retail/orderSuccess/orderSuccess',
                    })
                  }, 1000)
                }
              })
            }
          })
        } else {
          wx.showToast({
            title: '收款失败',
            duration: 1000,
          })
        }
        wx.hideLoading()
      }
    })
  },

  getPayEwm(type) {
    req({
      bNo: 3206,
      PayAmount: this.data.rechargeAmount,
      PayWay: type,
      ShopNo: this.data.ShopNo,
      OrderNo: this.data.OrderNo
    }, (data) => {
      wx.hideLoading();
      if (data.imgurl) {
        this.setData({
          showEwm: true,
          payPic: data.imgurl,
        })

        this.checkPayResult(data.CxONo, type)
      } else {
        wx.showModal({
          title: '提示',
          content: data.Result,
          showCancel: false,
        })
      };
    })
  },

  hideEwmDialog() {
    wx.showModal({
      title: '提示',
      content: '确认放弃收款吗？',
      success: res => {
        if (res.confirm) {
          this.setData({
            showDialog: false,
            showEwm: false
          })
          clearInterval(timer);
        }
      }
    })
  },

  checkPayResult(CxONo, type) {
    timer = setInterval(() => {
      req({
        bNo: 3207,
        OrderNo: this.data.OrderNo,
        CxONo,
        PayAmount: this.data.rechargeAmount,
        PayWay: type,
        opid: this.data.opInfo.n_ss_id,
      }, (data) => {
        if (data.Result == "支付完成") {
          clearInterval(timer);
          wx.removeStorage({
            key: 'result-list',
          })
          wx.removeStorage({
            key: 'mebInfo',
          })
          wx.showToast({
            title: '收款成功',
            mask: true,
            success: res => {
              setTimeout(() => {
                wx.redirectTo({
                  url: '/pages/retail/orderSuccess/orderSuccess',
                })
              }, 2000)
            }
          })
        }
      })
    }, 2000);
  },

  order() {
    if (this.data.amt < this.data.payAmount) {
      wx.showModal({
        title: '提示',
        content: '收款金额不足本单金额，请重新填写收款金额',
        showCancel: false,
      })
      return;
    };

    wx.showLoading({
      title: '',
    })
    var oIdx = this.data.ogList.length;
    var glist = this.data.ogList;
    for (var i = 0; i < this.data.gList.length; i++) {
      var C_GoodsTodo = "";
      var N_GoodsFeedJe = 0;
      var C_GoodsFeed = "";
      var tastArr = [];

      glist.push({
        "N_GOODS_ID": this.data.gList[i].ID,
        "N_NUM": this.data.gList[i].N_NUM,
        "N_REALPRICE": this.data.gList[i].SALE_PRICE,
      })
    }

    var Mebye = 0;
    if (this.data.mebInfo) {
      Mebye = this.data.mebInfo.N_MB_AMOUNT;
      if (!this.data.useBalance) {
        Mebye = 0;
      }
    }
    
    var str = `ShopNo&mebNo&opid&Mebye&glist=${this.data.ShopNo}*${this.data.mebno}*${this.data.opInfo.n_ss_id}*${Mebye}*${JSON.stringify(glist)}`;
    var md5 = util.md5(str);
    var data = {
      bNo: 4101,
      ShopNo: this.data.ShopNo,
      mebNo: this.data.mebno,
      glist: JSON.stringify(glist),
      Mebye,
      PayAmount: this.data.totalPrice,
      opid: this.data.opInfo.n_ss_id,
      MD5: md5.toUpperCase()
    }

    request(data, (data) => {
      wx.hideLoading();
      if (data.code === "100") {
        // 如果需要支付的金额为0，表示无需支付或者无需
        if (data.State != 3) {
          wx.hideLoading()
          this.data.rechargeAmount = data.PayAmount
          this.data.OrderNo = data.OrderNo;
          // this.choosePayType(data.OrderNo);
          if (this.data.payItem == 0) {
            this.regCash();
          } else if (this.data.payItem == 1) {
            this.getPayEwm(3);
          } else if (this.data.payItem == 2) {
            this.getPayEwm(1);
          }
          this.setData({
            OrderNo: data.OrderNo,
            rechargeAmount: data.PayAmount
          })
        } else {
          wx.removeStorage({
            key: 'result-list',
          })
          wx.removeStorage({
            key: 'mebInfo',
          })
          wx.showToast({
            title: '收款成功',
            mask: true,
            success: res => {
              setTimeout(() => {
                wx.redirectTo({
                  url: '/pages/retail/orderSuccess/orderSuccess',
                })
              }, 1000)
            }
          })
        }
      } else {
        wx.showModal({
          title: '提示',
          content: data.msg,
        })
      }
    })
  },

  hideDialog() {
    this.setData({
      setNumber: false,
      setMember: false,
    })
  },

  showDialog(ev) {
    var i = ev.currentTarget.dataset.i;
    if (i == 1) {
      this.setData({
        setMember: true,
      })
    } else {
      this.setData({
        setNumber: true,
      })
    }
  },
})